package com.suneee.quartz.init;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suneee.base.util.MD5Utils;
import com.suneee.base.util.StringUtil;
import com.suneee.base.util.SueCloudDateUtil;
import com.suneee.core.util.DateUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.quartz.dao.ScheduleConfigDao;
import com.suneee.quartz.dao.ScheduleTimeDao;
import com.suneee.quartz.entity.ScheduleConfig;
import com.suneee.quartz.entity.TmallOrderEn;
import com.suneee.store.dao.ShopStockDao;
import com.suneee.store.entity.ShopStock;
import com.suneee.trades.dao.TradesInfoDao;
import com.suneee.trades.entity.PromotionDetails;
import com.suneee.trades.entity.ScheduleTime;
import com.suneee.trades.entity.TradesInfo;
import com.suneee.trades.entity.TradesOrder;
import com.suneee.trades.init.TradesInfoInitialization;
import com.suneee.trades.resource.MergeStatus;
import com.suneee.trades.resource.OfflineStatus;
import com.taobao.api.response.TradesSoldIncrementGetResponse;

public class QuartzInit {
	
	private static final Logger logger = LoggerFactory.getLogger(QuartzInit.class);
	
	/**
	 * 同步店铺订单信息
	 * @param shopId
	 * @param enterpriseCode
	 * @param groupName
	 * @param shopMap
	 * @return
	 * @throws Exception
	 */
	public static TmallOrderEn  synAllShopOrder(Date startSynTime,Date endSynTime,Integer shopId,String enterpriseCode, String groupName,ScheduleTimeDao scheduleTimeDao,
			Map<String,String> shopMap,ShopStockDao shopStockDao,TradesInfoDao tradesInfoDao) throws Exception {
		List<TradesInfo> insertTradList = new ArrayList<TradesInfo>();
		List<TradesOrder> insertOrderList = new ArrayList<TradesOrder>();
		List<PromotionDetails> insertPromotionDetailsList = new ArrayList<PromotionDetails>();
		ScheduleTime dto = new ScheduleTime();
		if (!StringUtils.isEmpty(shopId.toString()))
			dto.setShopId(shopId);
//		if (!StringUtils.isEmpty(enterpriseCode))
//			dto.setEnterpriseCode(enterpriseCode);
		dto.setBusinessGroup(groupName);

		// 调用tmall接口查询订单,初次查询得到总行数
		TmallOrderEn tmallOrderEn = new TmallOrderEn();
		tmallOrderEn.setShopId(Integer.valueOf(shopId));
		tmallOrderEn.setEnterpriseCode(enterpriseCode);
		tmallOrderEn.setPageNo(1);
		tmallOrderEn.setPageSize(1);
		tmallOrderEn.setUseHasNext(false);
		
		//手工同步传入的时间
		if(startSynTime != null && endSynTime != null){
			tmallOrderEn.setStartModified(startSynTime);
			tmallOrderEn.setEndModified(endSynTime);
		}else{
			// 获取上一次更新的时间
			ScheduleTime schTime = scheduleTimeDao.getScheduleTime(dto);
			if(schTime != null)
				logger.info("上一次更新时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(schTime.getLastSynTime()));
			Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			if (schTime == null) {
				tmallOrderEn.setStartModified(date);
				tmallOrderEn.setEndModified(SueCloudDateUtil.getEndTime(date, 30));
			} else {
				tmallOrderEn.setStartModified(schTime.getLastSynTime());
				tmallOrderEn.setEndModified(SueCloudDateUtil.getEndTime(schTime.getLastSynTime(), 30));
			}
		}
		
		logger.info("当前修改结束时间:"+tmallOrderEn.getEndModified());
		
		tmallOrderEn.setShopMap(shopMap);
		TradesSoldIncrementGetResponse rsp = TmallInterface.getIncrementOrder(tmallOrderEn);
		if(!StringUtils.isBlank(rsp.getErrorCode())){
			tmallOrderEn.setIsSuccess(false);
		}else{
			tmallOrderEn.setIsSuccess(true);
		}
		Long totalResults = rsp.getTotalResults();
		logger.info("总行数:"+totalResults);
		if (totalResults != null && totalResults > 0) {
			int total = Integer.valueOf(totalResults.toString());
			int pageNum =  total / 50 + (total % 50 == 0 ? 0 : 1); 
			/** 分页查询tmall订单交易信息 */
			for (int i = 1; i <= pageNum; pageNum--) {
				tmallOrderEn.setPageNo(pageNum);
				tmallOrderEn.setPageSize(50);
				tmallOrderEn.setUseHasNext(true);
				tmallOrderEn.setShopMap(shopMap);
				TradesSoldIncrementGetResponse rspn = TmallInterface.getIncrementOrder(tmallOrderEn);
				TmallOrderEn returnEn = TradesInfoInitialization.initTradesInfo(rspn.getTrades(), tmallOrderEn);

				List<TradesInfo> curTradesInfoList = returnEn.getTradesInfoList();
				List<TradesOrder> curTradesOrderList = returnEn.getTradesOrderList();
				List<PromotionDetails> promotionDetailsList = returnEn.getPromotionDetailsList();

				insertTradList.addAll(curTradesInfoList);
				insertOrderList.addAll(curTradesOrderList);
				insertPromotionDetailsList.addAll(promotionDetailsList);
			}
			//查询数据库待审单数据
			List<TradesInfo> reviewTradList = tradesInfoDao.getDoInTrade(enterpriseCode);
			insertTradList.addAll(reviewTradList);//加入到理单数据中
			
			/** 理单，查找可合并订单 **/
			Map<String, List<String>> mapL = TradesInfoInitialization.richardTrades(insertTradList);

			/** 组装交易对应的行数据 **/
			Map<String, List<TradesOrder>> mapOrder = TradesInfoInitialization.assembleTradesOrder(insertOrderList);

			/** 对可合并的订单进行数据重组 **/
			List<TradesInfo> tdInfoList = new ArrayList<TradesInfo>();// 理单完成后插入数据库的集合
			StringBuffer remarkStr = new StringBuffer();
			for (TradesInfo tradesInfo : insertTradList) {
				String md5Key = MD5Utils.md5(tradesInfo.getReceiverName()+ tradesInfo.getReceiverCountry()+ tradesInfo.getReceiverState()
						+ tradesInfo.getReceiverCity()+ tradesInfo.getReceiverDistrict()+ tradesInfo.getReceiverTown()
						+ tradesInfo.getReceiverAddress()+ tradesInfo.getReceiverMobile());
				// 当前这个对象组合的key如果在map里面的list有值，并且size大于1,代表可以合单
				List<String> list = mapL.get(md5Key);
				if (list.size() > 1) {
					tradesInfo.setMergeStatus(MergeStatus.CAN_MERGE.name());
					tradesInfo.setMergeTids(StringUtil.listToString(list, ","));
					//if (!StringUtils.isEmpty(tradesInfo.getBuyerMemo())) {
					if (!StringUtils.isEmpty(tradesInfo.getBuyerMessage())) {
						remarkStr.append("买家有备注;" + "可合并订单("+ StringUtil.listToString(list, ",") + ")"+ ";");
					} else {
						remarkStr.append("可合并订单("+ StringUtil.listToString(list, ",") + ")"+ ";");
					}
				} else {
					// 处理备注信息
					//if (!StringUtils.isEmpty(tradesInfo.getBuyerMemo())) {
					if (!StringUtils.isEmpty(tradesInfo.getBuyerMessage())) {
						remarkStr.append("买家有备注");
					} else {
						remarkStr.append("无备注");
					}
				}
				// 检查店铺库存
				List<TradesOrder> tradOrdList = mapOrder.get(tradesInfo.getTid());// 交易对应的订单行
				if(tradOrdList != null){
					for (TradesOrder tradesOrder2 : tradOrdList) {
						ShopStock curShopStock = shopStockDao.getByShopIdSkuIdEpCode(Integer.valueOf(tradesOrder2.getOuterSkuId()),tmallOrderEn.getEnterpriseCode(),tmallOrderEn.getShopId());
						if (curShopStock != null) {
							if(curShopStock.getStock() == 0 || curShopStock.getStock() < 0)
							remarkStr.append("本地库存不足;");
						}
					}
				}
				tradesInfo.setRemark(remarkStr.toString());
				tradesInfo.setOfflineStatus(OfflineStatus.REVIEW_ORDER.name());
				tradesInfo.setAuditTime(DateUtils.getCurrentTimestamp());//审单时间
				tdInfoList.add(tradesInfo);
				remarkStr = new StringBuffer();
			}
			/** 组装交易优惠信息数据 **/
			Map<String, List<PromotionDetails>> mapPromtion = TradesInfoInitialization.assemblePromotion(insertPromotionDetailsList);

			/** 批量插入交易信息记录 批量插入订单行信息记录 插入订单优惠信息 循环order扣减库存 */
			tmallOrderEn.setTradesInfoList(tdInfoList);
			tmallOrderEn.setTradesOrderList(insertOrderList);
			tmallOrderEn.setMapOrder(mapOrder);
			tmallOrderEn.setMapPromtion(mapPromtion);
			//tradesInfoService.updateTrade(tmallOrderEn);

			tmallOrderEn.setTotalRows(totalResults);
		}
		return tmallOrderEn;
	}
	
}
